<!DOCTYPE html>
<html lang="en">
<head>
        <meta charset="utf-8" />
        <title>Part.3.B.4.regex</title>
        <link rel="stylesheet" href="/theme/css/main.css" />

        <!--[if IE]>
            <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
        <![endif]-->
</head>

<body id="index" class="home">
        <header id="banner" class="body">
                <h1><a href="/">PythonTutorials </a></h1>
                <nav><ul>
                    <li><a href="/category/cpp.html">cpp</a></li>
                    <li class="active"><a href="/category/python.html">python</a></li>
                </ul>
                </nav>
        </header><!-- /#banner -->
<section id="content" class="body">
  <article>
    <header>
      <h1 class="entry-title">
        <a href="/Part.3.B.4.regex.html" rel="bookmark"
           title="Permalink to Part.3.B.4.regex">Part.3.B.4.regex</a></h1>
    </header>

    <div class="entry-content">
<footer class="post-info">
        <span>Mon 06 April 2020</span>
<span>| tags: <a href="/tag/python.html">python</a><a href="/tag/progarmming.html">progarmming</a><a href="/tag/excel.html">Excel</a></span>
</footer><!-- /.post-info -->      <h1>正则表达式</h1>
<p>正则表达式本质上是个独立的语言，短小却格外强悍 —— 乃至于，如果你竟然没学会它的话，你的之前学的编程技能干脆与残疾无异。</p>
<p>Wikipedia 上对正则表达式的说明如下：</p>
<blockquote>
<p><strong>正则表达式</strong>（英语：Regular Expression，在代码中常简写为 regex、regexp 或 RE），又称<em>正规表示式</em>、<em>正规表示法</em>、<em>正规运算式</em>、<em>规则运算式</em>、<em>常规表示法</em>，是计算机科学的一个概念。正则表达式使用单个字符串来描述、匹配一系列符合某个句法规则的字符串。在很多文本编辑器里，正则表达式通常被用来检索、替换那些符合某个模式的文本。许多程序设计语言都支持利用正则表达式进行字符串操作。例如，在 Perl 中就内建了一个功能强大的正则表达式引擎。正则表达式这个概念最初是由 Unix 中的工具软件（例如 sed 和 grep）普及开的。</p>
</blockquote>
<p>以下是绝大多数翻译成中文的教程中对正则表达式进行讲解时所使用的描述：</p>
<blockquote>
<p>一个正则表达式（Regular Expression）通常被称为一个模式（Pattern）。</p>
</blockquote>
<p>我常常觉得当初要是它被翻译成 “规则表达式”，那么很可能初学者不会感到那么大的压力 —— 谁都一样，看着由 “每个都认识的字构成的词组” 却不能直观地想到它究竟是什么东西，都会感到莫名的压力。</p>
<p><strong>Regular</strong>，其实在它的众多语义中，取以下释义最符合 Regular Expression 的原意<a href='#fn1' name='fn1b'><sup>[1]</sup></a>：</p>
<blockquote>
<p>⑭ Linguistics 规则的 ▸ regular verbs 规则动词</p>
</blockquote>
<p>而 <strong>Pattern</strong> 这个词，在词典里有好几个对应的中文词汇：</p>
<blockquote>
<p>① 图案；② 式样；③ 图样；④ 榜样；⑤ 模式；⑥ 样品；⑦ 模子</p>
</blockquote>
<p>在当前语境之下，把 Pattern 翻译成 “模式”，显然不如 “模子” 更好（甚至连 “样品” 感觉都比 “模式” 更恰当）—— “模子” 这个词很直观啊，拿着一个模子去找与它一致的字符串…… “与规则一致”，英文用的是 <strong>Match</strong>，一般被翻译作 “匹配”。</p>
<p>在自学编程的过程中，处处都是这种语言翻译带来的迷惑、障碍，或者耽误。既然应该把 Regular Expression 理解为 “规则表达式” 更好，那其实吧，把 Pattern 直接理解为中文的 “<em>规则</em>”，可能更直观更准确，理解上更是毫无障碍：</p>
<blockquote>
<p>一个规则表达式（Regular Expression）通常被称为一个规则（Pattern）。</p>
</blockquote>
<p>那么，<strong>规则表达式</strong>里写的是什么呢？只能是<strong>规则</strong>了…… 到最后好像也就 “捕获”（Capture）这个词没什么歧义。</p>
<p>现在，我们已经把术语全部 “解密” 了，然后再看看下面的表述：</p>
<blockquote>
<p>我们可以用书写特定的规则，用来在文本中捕获与规则一致的字符串，而后对其进行操作……</p>
</blockquote>
<p>理解起来相当顺畅。</p>
<p>以下的 Python 代码中，<a href="https://regexper.com#%5Cwo%5Cw"><code>\wo\w</code></a> 就是一个<em>规则表达式</em>（或称为<em>规则</em>）；</p>
<p>而 <code>re.findall(pttn, str)</code> 的作用就是，在 <code>str</code> 里找到所有与这个<strong>规则</strong>（Pattern，模式）<strong>一致</strong>（Match，匹配）的字符串：</p>
<div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">re</span>
<span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;The quick brown fox jumps over the lazy dog&#39;</span>
<span class="n">pttn</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;\wo\w&#39;</span><span class="p">)</span>
<span class="n">re</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="n">pttn</span><span class="p">,</span> <span class="nb">str</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>[&#39;row&#39;, &#39;fox&#39;, &#39;dog&#39;]
</pre></div>


<p>总结一下：</p>
<blockquote>
<p><strong>规则表达式</strong>（Regular Expressions，通常缩写为 Regex）是最强大且不可或缺的文本处理工具 —— 它的用处就是在文本中<strong>扫描/搜索</strong>（Scan/Search）与某一<strong>规则</strong>（Pattern）<strong>匹配</strong>（Match，即，与规则一致）的所有实例，并且还可以按照规则<strong>捕获</strong>（Capture）其中的部分或者全部，对它们进行<strong>替换</strong>（Replace）。</p>
</blockquote>
<p>接下来为了避免歧义，我们干脆用 Regex 这个缩写，以及与它相关的英文单词：pattern, match, capture, replace(ment)……</p>
<p>有时，使用 Regex 并不是为了 Replace，而是为了检查格式，比如，可以用 Regex 检查用户输入的密码是否过于简单（比如，全部都由数字构成），比如可以用来验证用户输入的电话号码、证件号码是否符合特定格式等等。</p>
<p>另外，在自学的过程中，想尽一切办法把一切术语用简单直白的 “人话” 重新表述，是特别有效的促进进步的行为模式。</p>
<h2>视觉体验</h2>
<p>所谓百闻不如一见。</p>
<p>眼见为实 —— 想办法让一个陌生的概念视觉上直观，是突破大多学习障碍的最简单粗暴直接有效的方式。</p>
<p>我们最好先直接看看 Regex 的工作过程。以下，是用微软发行的代码编辑工具 Visual Studio Code 针对一小段文本使用若干条 Regex 进行匹配的过程：</p>
<p><img alt="123" src="https://raw.githubusercontent.com/selfteaching/the-craft-of-selfteaching/master/images/regex-test.gif?raw=true"></p>
<p>Python 的项目代码仓库里有一个很简短的 Demo 程序，叫 <a href="https://github.com/python/cpython/blob/master/Tools/demo/redemo.py"><code>redemo.py</code></a>，它使用 <a href="https://docs.python.org/3/library/tkinter.html">Tcl/Tk</a> 作为图形界面，也可以用来测试正则表达式。</p>
<p>它的代码地址是：</p>
<blockquote>
<p>https://raw.githubusercontent.com/python/cpython/master/Tools/demo/redemo.py</p>
</blockquote>
<p>它运行起来长成这样：</p>
<p><img alt="123" src="https://raw.githubusercontent.com/selfteaching/the-craft-of-selfteaching/master/images/redemo.png?raw=true"></p>
<p>目前（2019）网上最方便的 Regex 测试器，是 <a href="https://regex101.com">regex101.com</a>：</p>
<p>以下，就是在一段文本中，找出所有首写字母大写的词汇的<em>过程</em>，并将其先全部替换成小写，再将其全部替换为大写的过程；使用的正则表达式是 <code>([A-Z]\w+)</code>，替换表达式分别是 <code>\L$1</code> 和 <code>\U$1</code>：</p>
<p><img alt="123" src="https://raw.githubusercontent.com/selfteaching/the-craft-of-selfteaching/master/images/regex101.gif?raw=true"></p>
<p>这个网站太好了，所以，平日里我是用 <a href="https://github.com/jiahaog/nativefier">Nativefier</a> 工具将这个网站打包为一个 Mac Desktop App 使用。不过，它也有局限，就是被搜索文件略微大点就报错，说 <code>timeout</code>……</p>
<h2>准备工作</h2>
<p>我们需要个文本文件，用来当作练习使用正则表达式去搜索替换的目标。这个文件保存在当前的根目录，文件名称是：<code>regex-target-text-sample.txt</code>。</p>
<p>以下代码中，<code>pttn = r'beg[iau]ns?'</code> 这一句中的 <a href="https://regexper.com#beg[iau]ns?"><code>beg[iau]ns?</code></a> 就是 Regex 的 Pattern。</p>
<p><strong>注意</strong>：在 Python 代码中，写 Pattern 的时候，之所以要在字符串 <code>'...'</code> 之前加上 <code>r</code>，写成 <code>r'...'</code>，是因为如果不用 raw string 的话，那么，每个转义符号都要写成 <code>\\</code>；如果用 raw string，转义符号就可以直接使用 <code>\</code> 本身了…… 当然，如果你想搜索 <code>\</code> 这个符号本身的话，那么还是得写 <code>\\</code>。</p>
<p>而 <code>re.findall(pttn, str)</code> 的意思是说，把 <code>str</code> 中所有与 <code>pttn</code> 这个规则一致的字符串都找出来：</p>
<div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">re</span>
<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;regex-target-text-sample.txt&#39;</span><span class="p">,</span> <span class="s1">&#39;r&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
    <span class="nb">str</span> <span class="o">=</span> <span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
<span class="n">pttn</span> <span class="o">=</span> <span class="sa">r</span><span class="s1">&#39;beg[iau]ns?&#39;</span>
<span class="n">re</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="n">pttn</span><span class="p">,</span> <span class="nb">str</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>[&#39;begin&#39;, &#39;began&#39;, &#39;begun&#39;, &#39;begin&#39;]
</pre></div>


<p>文件 <code>regex-target-text-sample.txt</code> 中的内容如下：</p>
<div class="highlight"><pre><span></span><span class="p">&lt;</span><span class="nt">ol</span><span class="p">&gt;</span>
    <span class="p">&lt;</span><span class="nt">li</span><span class="p">&gt;&lt;</span><span class="nt">pre</span><span class="p">&gt;</span>begin began begun bigins begining<span class="p">&lt;/</span><span class="nt">pre</span><span class="p">&gt;&lt;/</span><span class="nt">li</span><span class="p">&gt;</span>
    <span class="p">&lt;</span><span class="nt">li</span><span class="p">&gt;&lt;</span><span class="nt">pre</span><span class="p">&gt;</span>google gooogle goooogle goooooogle<span class="p">&lt;/</span><span class="nt">pre</span><span class="p">&gt;&lt;/</span><span class="nt">li</span><span class="p">&gt;</span>
    <span class="p">&lt;</span><span class="nt">li</span><span class="p">&gt;&lt;</span><span class="nt">pre</span><span class="p">&gt;</span>coloured color coloring  colouring colored<span class="p">&lt;/</span><span class="nt">pre</span><span class="p">&gt;&lt;/</span><span class="nt">li</span><span class="p">&gt;</span>
    <span class="p">&lt;</span><span class="nt">li</span><span class="p">&gt;&lt;</span><span class="nt">pre</span><span class="p">&gt;</span>never ever verb however everest<span class="p">&lt;/</span><span class="nt">pre</span><span class="p">&gt;&lt;/</span><span class="nt">li</span><span class="p">&gt;</span>
    <span class="p">&lt;</span><span class="nt">li</span><span class="p">&gt;&lt;</span><span class="nt">pre</span><span class="p">&gt;</span>520 52000 5200000 520000000 520000000000<span class="p">&lt;/</span><span class="nt">pre</span><span class="p">&gt;&lt;/</span><span class="nt">li</span><span class="p">&gt;</span>
    <span class="p">&lt;</span><span class="nt">li</span><span class="p">&gt;&lt;</span><span class="nt">pre</span><span class="p">&gt;</span>error wonderer achroiocythaemia achroiocythemia<span class="p">&lt;/</span><span class="nt">pre</span><span class="p">&gt;&lt;/</span><span class="nt">li</span><span class="p">&gt;</span>
    <span class="p">&lt;</span><span class="nt">li</span><span class="p">&gt;&lt;</span><span class="nt">pre</span><span class="p">&gt;</span>The white dog wears a black hat.<span class="p">&lt;/</span><span class="nt">pre</span><span class="p">&gt;&lt;/</span><span class="nt">li</span><span class="p">&gt;</span>
    <span class="p">&lt;</span><span class="nt">li</span><span class="p">&gt;&lt;</span><span class="nt">pre</span><span class="p">&gt;</span>Handel, Händel, Haendel<span class="p">&lt;/</span><span class="nt">pre</span><span class="p">&gt;&lt;/</span><span class="nt">li</span><span class="p">&gt;</span>
<span class="p">&lt;/</span><span class="nt">ol</span><span class="p">&gt;</span>
<span class="p">&lt;</span><span class="nt">dl</span><span class="p">&gt;</span>(843) 542-4256<span class="p">&lt;/</span><span class="nt">dl</span><span class="p">&gt;</span> <span class="p">&lt;</span><span class="nt">dl</span><span class="p">&gt;</span>(431) 270-9664<span class="p">&lt;/</span><span class="nt">dl</span><span class="p">&gt;</span>
<span class="p">&lt;</span><span class="nt">dl</span><span class="p">&gt;</span>3336741162<span class="p">&lt;/</span><span class="nt">dl</span><span class="p">&gt;</span> <span class="p">&lt;</span><span class="nt">dl</span><span class="p">&gt;</span>3454953965<span class="p">&lt;/</span><span class="nt">dl</span><span class="p">&gt;</span>
<span class="p">&lt;</span><span class="nt">ul</span><span class="p">&gt;</span>
<span class="p">&lt;</span><span class="nt">li</span><span class="p">&gt;</span>peoplesr@live.com<span class="p">&lt;/</span><span class="nt">li</span><span class="p">&gt;</span> <span class="p">&lt;</span><span class="nt">li</span><span class="p">&gt;</span>jaxweb@hotmail.com<span class="p">&lt;/</span><span class="nt">li</span><span class="p">&gt;</span>
<span class="p">&lt;</span><span class="nt">li</span><span class="p">&gt;</span>dhwon@comcast.net<span class="p">&lt;/</span><span class="nt">li</span><span class="p">&gt;</span> <span class="p">&lt;</span><span class="nt">li</span><span class="p">&gt;</span>krueger@me.com<span class="p">&lt;/</span><span class="nt">li</span><span class="p">&gt;</span>
<span class="p">&lt;/</span><span class="nt">ul</span><span class="p">&gt;</span>
<span class="p">&lt;</span><span class="nt">h3</span><span class="p">&gt;</span>URLs<span class="p">&lt;/</span><span class="nt">h3</span><span class="p">&gt;</span>
https://docs.python.org/3/howto/regex.html
https://docs.python.org/3/library/re.html
<span class="p">&lt;</span><span class="nt">h3</span><span class="p">&gt;</span>passwords<span class="p">&lt;/</span><span class="nt">h3</span><span class="p">&gt;</span>
Pasw0rd~
i*Eh,GF67E
a$4Bh9XE<span class="err">&amp;</span>E
<span class="p">&lt;</span><span class="nt">h3</span><span class="p">&gt;</span>duplicate words<span class="p">&lt;/</span><span class="nt">h3</span><span class="p">&gt;</span>
<span class="p">&lt;</span><span class="nt">p</span><span class="p">&gt;</span>It&#39;s very very big.<span class="p">&lt;/</span><span class="nt">p</span><span class="p">&gt;</span>
<span class="p">&lt;</span><span class="nt">p</span><span class="p">&gt;</span>Keep it simple, simple, simple!<span class="p">&lt;/</span><span class="nt">p</span><span class="p">&gt;</span>
</pre></div>


<p>在以下的示例中，有时直接设定了 str 的值，而不是使用以上整个文本文件 —— 因为读者在阅读的时候，最好能直接看到被搜索的字符串。另外，如果使用整个文件，所得到的 Match 太多，也确实影响阅读。</p>
<h2>优先级</h2>
<p>毕竟，你已经不是 “啥都不懂” 的人了。你已经知道一个事实：编程语言无非是用来运算的。</p>
<p>所谓的运算，就有操作符（Operators）和操作元（Operands）—— 而操作符肯定是有优先级的，不然的话，那么多操作元和操作符放在一起，究竟先操作哪个呢？</p>
<p>Regex 也一样，它本身就是个迷你语言（Mini Language）。在 Regex 中，操作符肯定也有优先级。它的操作元有个专门的名称，<strong>原子</strong>（Atom）。</p>
<p>先大致看看它的操作符优先级，你就会对它有相当不错的了解：</p>
<table>
<thead>
<tr>
<th>排列</th>
<th>原子与操作符优先级</th>
<th>（从高到低）</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>转义符号 (Escaping Symbol)</td>
<td><code>\</code></td>
</tr>
<tr>
<td>2</td>
<td>分组、捕获 (Grouping or Capturing)</td>
<td><code>(...)</code> <code>(?:...)</code> <code>(?=...)</code> <code>(?!...)</code> <code>(?&lt;=...)</code> <code>(?&lt;!...)</code></td>
</tr>
<tr>
<td>3</td>
<td>数量 (Quantifiers)</td>
<td><code>a*</code> <code>a+</code> <code>a?</code> <code>a{n, m}</code></td>
</tr>
<tr>
<td>4</td>
<td>序列与定位（Sequence and Anchor）</td>
<td><code>abc</code> <code>^</code> <code>$</code> <code>\b</code> <code>\B</code></td>
</tr>
<tr>
<td>5</td>
<td>或（Alternation）</td>
<td><code>a\|b\|c</code></td>
</tr>
<tr>
<td>6</td>
<td>原子 (Atoms)</td>
<td><code>a</code> <code>[^abc]</code> <code>\t</code> <code>\r</code> <code>\n</code> <code>\d</code> <code>\D</code> <code>\s</code> <code>\S</code> <code>\w</code> <code>\W</code> <code>.</code></td>
</tr>
</tbody>
</table>
<p>当然，你若是在之前，没有自学过、理解过 Python（或者任何其它编程语言）表达式中的操作符优先级，那么一上来就看上面的表格不仅对你没有帮助，只能让你更迷惑。</p>
<p>—— 这就是理解能力逐步积累逐步加强的过程。</p>
<h2>原子</h2>
<p>在 Regex 的 Pattern 中，操作元，即，被运算的 “值”，被称为<strong>原子</strong>（Atom）。</p>
<h3>本义字符</h3>
<p>最基本的原子，就是本义字符，它们都是单个字符。</p>
<p>本义字符包括从 <code>a</code> 到 <code>z</code>，<code>A</code> 到 <code>Z</code>，<code>0</code> 到 <code>9</code>，还有 <code>_</code> —— 它们所代表的就是它们的字面值。</p>
<p>即，相当于，<code>string.ascii_letters</code> 和 <code>string.digits</code> 以及 <code>_</code>。</p>
<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="kn">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s2">&quot;all&quot;</span>

<span class="kn">import</span> <span class="nn">string</span>
<span class="n">string</span><span class="o">.</span><span class="n">ascii_letters</span>
<span class="n">string</span><span class="o">.</span><span class="n">digits</span>
</pre></div>


<div class="highlight"><pre><span></span>&#39;abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ&#39;
&#39;0123456789&#39;
</pre></div>


<p>以下字符在 Regex 中都有特殊含义：</p>
<blockquote>
<p><code>\</code> <code>+</code> <code>*</code> <code>.</code> <code>?</code> <code>-</code> <code>^</code> <code>$</code> <code>|</code> <code>(</code> <code>)</code> <code>[</code> <code>]</code> <code>{</code> <code>}</code> <code>&lt;</code> <code>&gt;</code></p>
</blockquote>
<p>当你在写 Regex 的时候，如果你需要搜索的字符不是本义字符，而是以上这些特殊字符时，<em>建议</em>都直接加上转义符号 <code>\</code> 来表示，比如，你想搜索 <code>'</code>，那你就写 <code>\'</code>，或者你想搜索 <code>#</code> 那你就写 <code>\#</code>（事实上，<code>#</code> 并不是 Regex 的特殊符号，所以，它之前的转义符号可有可无）—— 这对初学者来说可能是最安全的策略。</p>
<p>跟过往一样，所有的细节都很重要，它们就是需要花时间逐步熟悉到牢记。</p>
<h3>集合原子</h3>
<p>集合原子还是原子。</p>
<p>标示集合原子，使用方括号 <code>[]</code>。<code>[abc]</code> 的意思是说，“<code>a</code> or <code>b</code> or <code>c</code>”，即，<code>abc</code> 中的任意一个字符。</p>
<p>比如，<a href="https://regexper.com#beg[iau]n"><code>beg[iau]n</code></a> 能够代表 <code>begin</code>、<code>began</code>，以及 <code>begun</code>。</p>
<div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">re</span>

<span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;begin began begun bigins begining&#39;</span>
<span class="n">pttn</span> <span class="o">=</span> <span class="sa">r</span><span class="s1">&#39;beg[iau]n&#39;</span>
<span class="n">re</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="n">pttn</span><span class="p">,</span> <span class="nb">str</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>[&#39;begin&#39;, &#39;began&#39;, &#39;begun&#39;, &#39;begin&#39;]
</pre></div>


<p>在方括号中，我们可以使用两个操作符：<code>-</code>（区间）和 <code>^</code>（非）。</p>
<ul>
<li><code>[a-z]</code> 表示从小写字母 <code>a</code> 到小写字母 <code>z</code> 中的任意一个字符。</li>
<li><code>[^abc]</code> 表示 <code>abc</code> 以外的其它任意字符，即，非 <code>[abc]</code>。</li>
</ul>
<p>注意，一个集合原子中，<code>^</code> 符号只能用一次，只能紧跟在 <code>[</code> 之后。否则不起作用。</p>
<h3>类别原子</h3>
<p>类别原子，是指那些能够代表 “一类字符” 的原子，它们都得使用转义符号再加上另外一个符号表达，包括：</p>
<p><code>\d</code> 任意数字；等价于 <code>[0-9]</code></p>
<p><code>\D</code> 任意非数字；等价于 <code>[^0-9]</code></p>
<p><code>\w</code> 任意本义字符；等价于 <code>[a-zA-Z0-9_]</code></p>
<p><code>\W</code> 任意非本义字符；等价于 <code>[^a-zA-Z0-9_]</code></p>
<p><code>\s</code> 任意空白；相当于 <code>[ \f\n\r\t\v]</code>（注意，方括号内第一个字符是空格符号）</p>
<p><code>\S</code> 任意非空白；相当于 <code>[^ \f\n\r\t\v]</code>（注意，紧随 <code>^</code> 之后的是一个空格符号）</p>
<p><code>.</code> 除 <code>\r</code> <code>\n</code> 之外的任意字符；相当于 <code>[^\r\n]</code></p>
<p>类别原子挺好记忆的，如果你知道各个字母是哪个词的首字母的话：</p>
<blockquote>
<ul>
<li><code>d</code> 是 digits</li>
<li><code>w</code> 是 word characters</li>
<li><code>s</code> 是 spaces</li>
</ul>
</blockquote>
<p>另外，在空白的集合 <code>[ \f\n\r\t\v]</code> 中：<code>\f</code> 是分页符；<code>\n</code> <code>\r</code> 是换行符；<code>\t</code> 是制表符；<code>\v</code> 是纵向制表符（很少用到）。各种关于空白的转义符也同样挺好记忆的，如果你知道各个字母是那个词的首字母的话：</p>
<blockquote>
<ul>
<li><code>f</code> 是 flip</li>
<li><code>n</code> 是 new line</li>
<li><code>r</code> 是 return</li>
<li><code>t</code> 是 tab</li>
<li><code>v</code> 是 vertical tab</li>
</ul>
</blockquote>
<div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">re</span>

<span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;&lt;dl&gt;(843) 542-4256&lt;/dl&gt; &lt;dl&gt;(431) 270-9664&lt;/dl&gt;&#39;</span>
<span class="n">pttn</span> <span class="o">=</span> <span class="sa">r</span><span class="s1">&#39;\d\d\d\-&#39;</span>
<span class="n">re</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="n">pttn</span><span class="p">,</span> <span class="nb">str</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>[&#39;542-&#39;, &#39;270-&#39;]
</pre></div>


<h3>边界原子</h3>
<p>我们可以用边界原子指定边界。也可以称作 “定位操作符”。</p>
<p><code>^</code> 匹配被搜索字符串的开始位置；</p>
<p><code>$</code> 匹配被搜索字符串的结束位置；</p>
<p><code>\b</code> 匹配单词的边界；<a href="https://regexper.com#er%5Cb"><code>er\b</code></a>，能匹配 <code>coder</code> 中的 <code>er</code>，却不能匹配 <code>error</code> 中的 <code>er</code>；</p>
<p><code>\B</code> 匹配非单词边界；<a href="https://regexper.com#er%5CB"><code>er\B</code></a>，能匹配 <code>error</code> 中的 <code>er</code>，却不能匹配 <code>coder</code> 中的 <code>er</code>。</p>
<div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">re</span>

<span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;never ever verb however everest&#39;</span>
<span class="n">pttn</span> <span class="o">=</span> <span class="sa">r</span><span class="s1">&#39;er\b&#39;</span>
<span class="n">re</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="n">pttn</span><span class="p">,</span> <span class="nb">str</span><span class="p">)</span>
<span class="n">pttn</span> <span class="o">=</span> <span class="sa">r</span><span class="s1">&#39;er\B&#39;</span>
<span class="n">re</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="n">pttn</span><span class="p">,</span> <span class="nb">str</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span><span class="k">[&#39;er&#39;, &#39;er&#39;, &#39;er&#39;]</span>
<span class="k">[&#39;er&#39;, &#39;er&#39;]</span>
</pre></div>


<p><strong>注意</strong>：<code>^</code> 和 <code>$</code> 在 Python 语言中被 <code>\A</code> 和 <code>\Z</code> 替代。</p>
<p>事实上，每种语言或多或少都对 Regex 有自己的定制。不过，本章讨论的绝大多数细节，都是通用的。</p>
<h3>组合原子</h3>
<p>我们可以用圆括号 <code>()</code> 将多个单字符原子组合成一个原子 —— 这么做的结果是，<code>()</code> 内的字符串将被当作一整个原子，可以被随后我们要讲解的数量操作符操作。</p>
<p>另外，<code>()</code> 这个操作符，有两个作用：<strong>组合</strong>（Grouping），就是我们刚刚讲到的作用；而另外一个作用是<strong>捕获</strong>（Capturing)，后面会讲到。</p>
<p>注意区别，<a href="https://regexper.com#er"><code>er</code></a>、<a href="https://regexper.com#[er]"><code>[er]</code></a> 和 [<code>(er)</code>](https://regexper.com#(er) 各不相同。</p>
<blockquote>
<ul>
<li><code>er</code> 是两个原子，<code>'e'</code> 和紧随其后的 <code>'r'</code></li>
<li><code>[er]</code> 是一个原子，或者 <code>'e'</code> 或者 <code>'r'</code>；</li>
<li><code>(er)</code> 是一个原子，<code>'er'</code></li>
</ul>
</blockquote>
<p>下一节中讲到数量操作符的时候，会再次强调这点。</p>
<h2>数量操作符</h2>
<p>数量操作符有：<code>+</code> <code>?</code> <code>*</code> <code>{n, m}</code>。</p>
<p>它们是用来限定位于它们之前的原子允许出现的个数；不加数量限定则代表出现一次且仅出现一次：</p>
<p><code>+</code> 代表前面的原子必须至少出现一次，即：<code>出现次数 ≧ 1</code></p>
<blockquote>
<p>例如，<a href="https://regexper.com#go+gle"><code>go+gle</code></a>可以匹配 <code>google</code> <code>gooogle</code> <code>goooogle</code> 等；</p>
</blockquote>
<p><code>?</code> 代表前面的原子最多只可以出现一次，即：<code>0 ≦ 出现次数 ≦ 1</code></p>
<blockquote>
<p>例如，<a href="https://regexper.com#colou?red"><code>colou?red</code></a>可以匹配 <code>colored</code> 或者 <code>coloured</code>;</p>
</blockquote>
<p><code>*</code> 代表前面的原子可以不出现，也可以出现一次或者多次，即：<code>出现次数 ≧ 0</code></p>
<blockquote>
<p>例如，<a href="https://regexper.com#520*"><code>520*</code></a>可以匹配 <code>52</code> <code>520</code> <code>52000</code> <code>5200000</code> <code>520000000000</code> 等。</p>
</blockquote>
<p><code>{n}</code> 之前的原子出现确定的 <code>n</code> 次；</p>
<p><code>{n,}</code> 之前的原子出现至少 <code>n</code> 次；</p>
<p><code>{n, m}</code> 之前的原子出现至少 <code>n</code> 次，至多 <code>m</code> 次</p>
<blockquote>
<p>例如，<a href="https://regexper.com#go%7B2,5%7Dgle"><code>go{2,5}gle</code></a>，能匹配 <code>google</code> <code>gooogle</code> <code>goooogle</code> 或 <code>gooooogle</code>，但不能匹配 <code>gogle</code> 和 <code>gooooooogle</code></p>
</blockquote>
<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="kn">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s2">&quot;all&quot;</span>

<span class="kn">import</span> <span class="nn">re</span>
<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;regex-target-text-sample.txt&#39;</span><span class="p">,</span> <span class="s1">&#39;r&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
    <span class="nb">str</span> <span class="o">=</span> <span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>

<span class="n">pttn</span> <span class="o">=</span> <span class="sa">r</span><span class="s1">&#39;go+gle&#39;</span>
<span class="n">re</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="n">pttn</span><span class="p">,</span> <span class="nb">str</span><span class="p">)</span>

<span class="n">pttn</span> <span class="o">=</span> <span class="sa">r</span><span class="s1">&#39;go{2,5}gle&#39;</span>
<span class="n">re</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="n">pttn</span><span class="p">,</span> <span class="nb">str</span><span class="p">)</span>

<span class="n">pttn</span> <span class="o">=</span> <span class="sa">r</span><span class="s1">&#39;colou?red&#39;</span>
<span class="n">re</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="n">pttn</span><span class="p">,</span> <span class="nb">str</span><span class="p">)</span>

<span class="n">pttn</span> <span class="o">=</span> <span class="sa">r</span><span class="s1">&#39;520*&#39;</span>
<span class="n">re</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="n">pttn</span><span class="p">,</span> <span class="nb">str</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span><span class="k">[&#39;google&#39;, &#39;gooogle&#39;, &#39;goooogle&#39;, &#39;goooooogle&#39;]</span>

<span class="k">[&#39;google&#39;, &#39;gooogle&#39;, &#39;goooogle&#39;]</span>

<span class="k">[&#39;coloured&#39;, &#39;colored&#39;]</span>

<span class="k">[&#39;520&#39;, &#39;52000&#39;, &#39;5200000&#39;, &#39;520000000&#39;, &#39;520000000000&#39;]</span>
</pre></div>


<p>数量操作符是对它之前的原子进行操作的，换言之，数量操作符的操作元是操作符之前的原子。</p>
<p>上一节提到，要注意区别：<code>er</code>、<code>[er]</code> 和 <code>(er)</code> 各不相同。</p>
<blockquote>
<ul>
<li><code>er</code> 是两个原子，<code>'e'</code> 之后 <code>'r'</code></li>
<li><code>[er]</code> 是一个原子，或者 <code>'e'</code> 或者 <code>'r'</code>；</li>
<li><code>(er)</code> 是一个原子，<code>'er'</code></li>
</ul>
</blockquote>
<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="kn">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s2">&quot;all&quot;</span>

<span class="kn">import</span> <span class="nn">re</span>

<span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;error wonderer severeness&#39;</span>

<span class="n">pttn</span> <span class="o">=</span> <span class="sa">r</span><span class="s1">&#39;er&#39;</span>
<span class="n">re</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="n">pttn</span><span class="p">,</span> <span class="nb">str</span><span class="p">)</span>

<span class="n">pttn</span> <span class="o">=</span> <span class="sa">r</span><span class="s1">&#39;[er]&#39;</span>
<span class="n">re</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="n">pttn</span><span class="p">,</span> <span class="nb">str</span><span class="p">)</span>

<span class="n">pttn</span> <span class="o">=</span> <span class="sa">r</span><span class="s1">&#39;(er)&#39;</span>
<span class="n">re</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="n">pttn</span><span class="p">,</span> <span class="nb">str</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span><span class="k">[&#39;er&#39;, &#39;er&#39;, &#39;er&#39;, &#39;er&#39;]</span>
<span class="k">[&#39;e&#39;, &#39;r&#39;, &#39;r&#39;, &#39;r&#39;, &#39;e&#39;, &#39;r&#39;, &#39;e&#39;, &#39;r&#39;, &#39;e&#39;, &#39;e&#39;, &#39;r&#39;, &#39;e&#39;, &#39;e&#39;]</span>
<span class="k">[&#39;er&#39;, &#39;er&#39;, &#39;er&#39;, &#39;er&#39;]</span>
</pre></div>


<p>在以上的例子中，看不出 <code>er</code> 和 <code>(er)</code> 的区别，但是，加上数量操作符就不一样了 —— 因为<em>数量操作符只对它之前的那一个原子进行操作</em>：</p>
<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="kn">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s2">&quot;all&quot;</span>

<span class="kn">import</span> <span class="nn">re</span>

<span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;error wonderer severeness&#39;</span>

<span class="n">pttn</span> <span class="o">=</span> <span class="sa">r</span><span class="s1">&#39;er+&#39;</span>
<span class="n">re</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="n">pttn</span><span class="p">,</span> <span class="nb">str</span><span class="p">)</span>

<span class="n">pttn</span> <span class="o">=</span> <span class="sa">r</span><span class="s1">&#39;[er]+&#39;</span>
<span class="n">re</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="n">pttn</span><span class="p">,</span> <span class="nb">str</span><span class="p">)</span>

<span class="n">pttn</span> <span class="o">=</span> <span class="sa">r</span><span class="s1">&#39;(er)+&#39;</span>
<span class="n">re</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="n">pttn</span><span class="p">,</span> <span class="nb">str</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span><span class="k">[&#39;err&#39;, &#39;er&#39;, &#39;er&#39;, &#39;er&#39;]</span>
<span class="k">[&#39;err&#39;, &#39;r&#39;, &#39;erer&#39;, &#39;e&#39;, &#39;ere&#39;, &#39;e&#39;]</span>
<span class="k">[&#39;er&#39;, &#39;er&#39;, &#39;er&#39;]</span>
</pre></div>


<h2>或操作符 <code>|</code></h2>
<p>或操作符 <code>|</code> 是所有操作符中优先级最低的，数量操作符的优先级比它高，所以，在 <code>|</code> 前后的原子被数量操作符（如果有的话）操作之后才交给 <code>|</code> 操作。</p>
<p>于是，<a href="https://regexper.com#begin%7Cbegan%7Cbegun"><code>begin|began|begun</code></a> 能够匹配 <code>begin</code> 或 <code>began</code> 或 <code>begun</code>。</p>
<div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">re</span>

<span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;begin began begun begins beginn&#39;</span>
<span class="n">pttn</span> <span class="o">=</span> <span class="sa">r</span><span class="s1">&#39;begin|began|begun&#39;</span>
<span class="n">re</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="n">pttn</span><span class="p">,</span> <span class="nb">str</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>[&#39;begin&#39;, &#39;began&#39;, &#39;begun&#39;, &#39;begin&#39;, &#39;begin&#39;]
</pre></div>


<p>在集合原子中（即，<code>[]</code> 内的原子）各个原子之间的关系，只有 “或” —— 相当于方括号中的每个原子之间都有一个被省略的 <code>|</code>。</p>
<p><strong>注意</strong>：方括号的 <code>|</code> 不被当作特殊符号，而是被当作 <code>|</code> 这个符号本身。在方括号中的圆括号，也被当作圆括号 <code>()</code> 本身，而无分组含义。</p>
<div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="kn">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s2">&quot;all&quot;</span>

<span class="kn">import</span> <span class="nn">re</span>

<span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;achroiocythaemia achroiocythemia a|e&#39;</span>
<span class="n">pttn</span> <span class="o">=</span> <span class="sa">r</span><span class="s1">&#39;[a|ae]&#39;</span>
<span class="n">re</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="n">pttn</span><span class="p">,</span> <span class="nb">str</span><span class="p">)</span>

<span class="n">pttn</span> <span class="o">=</span> <span class="sa">r</span><span class="s1">&#39;[a|e]&#39;</span>
<span class="n">re</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="n">pttn</span><span class="p">,</span> <span class="nb">str</span><span class="p">)</span>

<span class="n">pttn</span> <span class="o">=</span> <span class="sa">r</span><span class="s1">&#39;[ae]&#39;</span>
<span class="n">re</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="n">pttn</span><span class="p">,</span> <span class="nb">str</span><span class="p">)</span>

<span class="n">pttn</span> <span class="o">=</span> <span class="sa">r</span><span class="s1">&#39;[(ae)]&#39;</span>
<span class="n">re</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="n">pttn</span><span class="p">,</span> <span class="nb">str</span><span class="p">)</span>

<span class="n">pttn</span> <span class="o">=</span> <span class="sa">r</span><span class="s1">&#39;[a|ae|(ae)]&#39;</span>
<span class="n">re</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="n">pttn</span><span class="p">,</span> <span class="nb">str</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span>[&#39;a&#39;, &#39;a&#39;, &#39;e&#39;, &#39;a&#39;, &#39;a&#39;, &#39;e&#39;, &#39;a&#39;, &#39;a&#39;, &#39;|&#39;, &#39;e&#39;]
</pre></div>


<h2>匹配并捕获</h2>
<p>捕获（Capture），使用的是圆括号 <code>()</code>。使用圆括号得到的匹配的值被暂存成一个带有索引的列表，第一个是 <code>$1</code>，第二个是 <code>$2</code>…… 以此类推。随后，我们可以在替换的过程中使用 <code>$1</code> <code>$2</code> 中所保存的值。</p>
<p><strong>注意</strong>：在 Python 语言中调用 <code>re</code> 模块之后，在 <code>re.sub()</code> 中调用被匹配的值，用的索引方法是 <code>\1</code>、<code>\2</code>…… 以此类推。</p>
<div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">re</span>
<span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;The white dog wears a black hat.&#39;</span>
<span class="n">pttn</span> <span class="o">=</span> <span class="sa">r</span><span class="s1">&#39;The (white|black) dog wears a (white|black) hat.&#39;</span>
<span class="n">re</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="n">pttn</span><span class="p">,</span> <span class="nb">str</span><span class="p">)</span>

<span class="n">repl</span> <span class="o">=</span> <span class="sa">r</span><span class="s1">&#39;The \2 dog wears a \1 hat.&#39;</span>
<span class="n">re</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="n">pttn</span><span class="p">,</span> <span class="n">repl</span><span class="p">,</span> <span class="nb">str</span><span class="p">)</span>

<span class="n">repl</span> <span class="o">=</span> <span class="sa">r</span><span class="s1">&#39;The \1 dog wears a \1 hat.&#39;</span>
<span class="n">re</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="n">pttn</span><span class="p">,</span> <span class="n">repl</span><span class="p">,</span> <span class="nb">str</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span><span class="k">[(&#39;white&#39;, &#39;black&#39;)]</span>
<span class="na">&#39;The black dog wears a white hat.&#39;</span>
<span class="na">&#39;The white dog wears a white hat.&#39;</span>
</pre></div>


<h2>非捕获匹配</h2>
<p>有时，你并不想捕获圆括号中的内容，在那个地方你使用括号的目的只是分组，而非捕获，那么，你就在圆括号内最开头加上 <code>?:</code> —— <code>(?:...)</code>：</p>
<div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">re</span>
<span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;The white dog wears a black hat.&#39;</span>
<span class="n">pttn</span> <span class="o">=</span> <span class="sa">r</span><span class="s1">&#39;The (?:white|black) dog wears a (white|black) hat.&#39;</span>
<span class="n">re</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="n">pttn</span><span class="p">,</span> <span class="nb">str</span><span class="p">)</span>                   <span class="c1"># 只捕获了一处，也就是说只有一个值将来可以被引用</span>

<span class="n">repl</span> <span class="o">=</span> <span class="sa">r</span><span class="s1">&#39;The \1 dog wears a \1 hat.&#39;</span>    <span class="c1"># 之前的一处捕获，在替换时可被多次引用</span>
<span class="err">書評</span>
<span class="n">re</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="n">pttn</span><span class="p">,</span> <span class="n">repl</span><span class="p">,</span> <span class="nb">str</span><span class="p">)</span>
</pre></div>


<div class="highlight"><pre><span></span><span class="k">[&#39;black&#39;]</span>

<span class="na">&#39;The black dog wears a black hat.&#39;</span>
</pre></div>


<p>在 Python 代码中使用正则表达式，匹配和捕获以及随后的替换，有更灵活的方式，因为可以对那些值直接编程。<code>re.sub()</code> 中，<code>repl</code> 参数甚至可以接收另外一个函数作为参数 —— 以后你肯定会自行认真阅读以下页面中的所有内容：</p>
<blockquote>
<p>https://docs.python.org/3/library/re.html</p>
</blockquote>
<p>非捕获匹配，还有若干个操作符：</p>
<p><code>(?=pattern)</code></p>
<blockquote>
<p>正向肯定预查（look ahead positive assert），在任何匹配规则的字符串开始处匹配查找字符串。这是一个非获取匹配，也就是说，该匹配不需要获取供以后使用。例如，<a href="https://regexper.com#%60Windows(?=95%7C98%7CNT%7C2000)%60"><code>Windows(?=95|98|NT|2000)</code></a>
能匹配 <code>Windows2000</code> 中的 <code>Windows</code>，但不能匹配 <code>Windows3.1</code> 中的 <code>Windows</code>。预查不消耗字符，也就是说，在一个匹配发生后，在最后一次匹配之后立即开始下一次匹配的搜索，而不是从包含预查的字符之后开始。</p>
</blockquote>
<p><code>(?!pattern)</code></p>
<blockquote>
<p>正向否定预查（negative assert），在任何不匹配规则的字符串开始处匹配查找字符串。这是一个非获取匹配，也就是说，该匹配不需要获取供以后使用。例如<a href="https://regexper.com#Windows(?=95%7C98%7CNT%7C2000)"><code>Windows(?!95|98|NT|2000)</code></a>
能匹配 <code>Windows3.1</code> 中的 <code>Windows</code>，但不能匹配 <code>Windows2000</code> 中的 <code>Windows</code>。预查不消耗字符，也就是说，在一个匹配发生后，在最后一次匹配之后立即开始下一次匹配的搜索，而不是从包含预查的字符之后开始。</p>
</blockquote>
<p><code>(?&lt;=pattern)</code></p>
<blockquote>
<p>反向（look behind）肯定预查，与正向肯定预查类似，只是方向相反。例如，<a href="https://regexper.com#(?%3C=95%7C98%7CNT%7C2000)Windows"><code>(?&lt;=95|98|NT|2000)Windows</code></a>
能匹配 <code>2000Windows</code> 中的 <code>Windows</code>，但不能匹配 <code>3.1Windows</code> 中的 <code>Windows</code>。</p>
</blockquote>
<p><code>(?&lt;!pattern)</code></p>
<blockquote>
<p>反向否定预查，与正向否定预查类似，只是方向相反。例如 <code>(?&lt;!95|98|NT|2000)Windows</code>
能匹配 <code>3.1Windows</code> 中的 <code>Windows</code>，但不能匹配 <code>2000Windows</code> 中的 <code>Windows</code>。</p>
</blockquote>
<h2>控制标记</h2>
<p>有几个全局控制标记（Flag）需要了解，其中最常默认指定的有 <code>G</code> 和 <code>M</code>：</p>
<p><code>A</code>/<code>ASCII</code>，默认为 <code>False</code></p>
<blockquote>
<ul>
<li><code>\d</code>, <code>\D</code>, <code>\w</code>, <code>\W</code>, <code>\s</code>, <code>\S</code>, <code>\b</code>, 和 <code>\B</code> 等只限于 ASCII 字符</li>
<li>行内写法：<code>(?a)</code></li>
<li>Python re 模块中的常量：<code>re.A</code> <code>re.ASCII</code></li>
</ul>
</blockquote>
<p><code>I</code>/<code>IGNORECASE</code>，默认为 <code>False</code></p>
<blockquote>
<ul>
<li>忽略字母大小写</li>
<li>行内写法：<code>(?i)</code></li>
<li>Python re 模块中的常量：<code>re.I</code> <code>re.IGNORECASE</code></li>
</ul>
</blockquote>
<p><code>G</code>/<code>GLOBAL</code>，默认为 <code>True</code></p>
<blockquote>
<ul>
<li>找到第一个 match 之后不返回</li>
<li>行内写法：<code>(?g)</code></li>
<li>Python re 模块中这个标记不能更改，默认为 TRUE</li>
</ul>
</blockquote>
<p><code>L</code>/<code>LOCALE</code>，默认为 <code>False</code></p>
<blockquote>
<ul>
<li>由本地语言设置决定 <code>\d</code>, <code>\D</code>, <code>\w</code>, <code>\W</code>, <code>\s</code>, <code>\S</code>, <code>\b</code>, 和 <code>\B</code> 等等的内容</li>
<li>行内写法：<code>(?L)</code></li>
<li>Python re 模块中的常量：<code>re.L</code> <code>re.LOCALE</code></li>
</ul>
</blockquote>
<p><code>M</code>/<code>MULTILINE</code>，默认为 <code>True</code></p>
<blockquote>
<ul>
<li>使用本标志后，<code>^</code> 和 <code>$</code> 匹配行首和行尾时，会增加换行符之前和之后的位置。</li>
<li>行内写法：<code>(?m)</code></li>
<li>Python re 模块中的常量：<code>re.M</code> <code>re.MULTILINE</code></li>
</ul>
</blockquote>
<p><code>S</code>/<code>DOTALL</code>，默认为 <code>False</code></p>
<blockquote>
<ul>
<li>使 <code>.</code> 完全匹配任何字符，包括换行；没有这个标志，<code>.</code> 匹配除了 <code>n</code> <code>r</code> 之外的任何字符。</li>
<li>行内写法：<code>(?s)</code></li>
<li>Python re 模块中的常量：<code>re.S</code> <code>re.DOTALL</code></li>
</ul>
</blockquote>
<p><code>X</code>/<code>VERBOSE</code>，默认为 <code>False</code></p>
<blockquote>
<ul>
<li>当该标志被指定时，Pattern 中的的空白符会被忽略，除非该空白符在圆括号或方括号中，或在反斜杠 <code>\</code> 之后。这样做的结果是允许将注释写入 Pattern，这些注释会被 Regex 解析引擎忽略。注释用 <code>#</code> 号来标识，不过该符号不能在字符串或反斜杠之后。</li>
<li>行内写法：<code>(?x)</code></li>
<li>Python re 模块中的常量：<code>re.X</code> <code>re.VERBOSE</code></li>
</ul>
</blockquote>
<h2>几个最常用的 Regex</h2>
<p>以下是几个常用的 Regex<a href='#fn2' name='fn2b'><sup>[2]</sup></a>，值得保存：</p>
<ul>
<li>
<p>matching username</p>
<blockquote>
<p><a href="https://regexper.com#/%5E[a-z0-9_-]%7B3,16%7D$/"><code>/^[a-z0-9_-]{3,16}$/</code></a></p>
</blockquote>
</li>
<li>
<p>matching password<a href='#fn3' name='fn3b'><sup>[3]</sup></a></p>
<blockquote>
<p><a href="https://regexper.com#/%5E[a-z0-9_-]%7B6,18%7D$/"><code>/^[a-z0-9_-]{6,18}$/</code></a></p>
</blockquote>
</li>
<li>
<p>matching a HEX value</p>
<blockquote>
<p><a href="https://regexper.com#/%5E#?([a-f0-9]%7B6%7D%7C[a-f0-9]%7B3%7D)$/"><code>/^#?([a-f0-9]{6}|[a-f0-9]{3})$/</code></a></p>
</blockquote>
</li>
<li>
<p>matching a slug</p>
<blockquote>
<p><a href="https://regexper.com#/%5E[a-z0-9-]+$/"><code>/^[a-z0-9-]+$/</code></a></p>
</blockquote>
</li>
<li>
<p>matching email address</p>
<blockquote>
<p><a href="https://regexper.com#/%5E([a-z0-9_%5C.-]+)@([%5Cda-z%5C.-]+)%5C.([a-z%5C.]%7B2,6%7D)$/"><code>/^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/</code></a></p>
</blockquote>
</li>
<li>
<p>matching a URL</p>
<blockquote>
<p><a href="https://regexper.com#/%5E(https?:%5C/%5C/)?([%5Cda-z%5C.-]+)%5C.([a-z%5C.]%7B2,6%7D)([%5C/%5Cw%20%5C.-]*)*%5C/?$/"><code>/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/</code></a></p>
</blockquote>
</li>
<li>
<p>matching an IP address</p>
<blockquote>
<p><a href="https://regexper.com/#%2F%5E%28%3F%3A%28%3F%3A25%5B0-5%5D%7C2%5B0-4%5D%5B0-9%5D%7C%5B01%5D%3F%5B0-9%5D%5B0-9%5D%3F%29%5C.%29%7B3%7D%28%3F%3A25%5B0-5%5D%7C2%5B0-4%5D%5B0-9%5D%7C%5B01%5D%3F%5B0-9%5D%5B0-9%5D%3F%29%24%2F"><code>/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/</code></a></p>
</blockquote>
</li>
<li>
<p>matching a HTML tag</p>
<blockquote>
<p><a href="https://regexper.com/#%2F%5E&lt;%28%5Ba-z%5D%2B%29%28%5B%5E&lt;%5D%2B%29*%28%3F%3A&gt;%28.*%29&lt;%5C%2F%5C1&gt;%7C%5Cs%2B%5C%2F&gt;%29%24%2F"><code>/^&lt;([a-z]+)([^&lt;]+)*(?:&gt;(.*)&lt;\/\1&gt;|\s+\/&gt;)$/</code></a></p>
</blockquote>
</li>
</ul>
<p>对了，告诉你一个小秘密：</p>
<blockquote>
<p>以上的正则表达式，点击都能连接到 <a href="https://regexper.com">regexper.com</a>，在那里你能查看这些正则表达式的图形化示意图。另外，本文中，处于 markdown cell 的绝大多数正则表达式都有这样的连接…… 你可以重读的时候试试。</p>
</blockquote>
<p>写 Regex 最烧脑的地方在于 “使其全面” —— 要考虑到各种意外情况。</p>
<p>当然，除非必要，也不要在 “全面” 这事上面花太多时间 —— 给你看一个据说是 “最大程度上能够匹配所有 email 地址的 Regex” <a href='#fn4' name='fn4b'><sup>[4]</sup></a>，我都懒得测试的一个正则表达式：</p>
<div class="highlight"><pre><span></span>(?:(?:\r\n)?[ \t])*(?:(?:(?:[^()&lt;&gt;@,;:\\&quot;.\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t]
)+|\Z|(?=[\[&quot;()&lt;&gt;@,;:\\&quot;.\[\]]))|&quot;(?:[^\&quot;\r\\]|\\.|(?:(?:\r\n)?[ \t]))*&quot;(?:(?:
\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()&lt;&gt;@,;:\\&quot;.\[\] \000-\031]+(?:(?:(
?:\r\n)?[ \t])+|\Z|(?=[\[&quot;()&lt;&gt;@,;:\\&quot;.\[\]]))|&quot;(?:[^\&quot;\r\\]|\\.|(?:(?:\r\n)?[
\t]))*&quot;(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()&lt;&gt;@,;:\\&quot;.\[\] \000-\0
31]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[&quot;()&lt;&gt;@,;:\\&quot;.\[\]]))|\[([^\[\]\r\\]|\\.)*\
](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()&lt;&gt;@,;:\\&quot;.\[\] \000-\031]+
(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[&quot;()&lt;&gt;@,;:\\&quot;.\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:
(?:\r\n)?[ \t])*))*|(?:[^()&lt;&gt;@,;:\\&quot;.\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z
|(?=[\[&quot;()&lt;&gt;@,;:\\&quot;.\[\]]))|&quot;(?:[^\&quot;\r\\]|\\.|(?:(?:\r\n)?[ \t]))*&quot;(?:(?:\r\n)
?[ \t])*)*\&lt;(?:(?:\r\n)?[ \t])*(?:@(?:[^()&lt;&gt;@,;:\\&quot;.\[\] \000-\031]+(?:(?:(?:\
r\n)?[ \t])+|\Z|(?=[\[&quot;()&lt;&gt;@,;:\\&quot;.\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[
 \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()&lt;&gt;@,;:\\&quot;.\[\] \000-\031]+(?:(?:(?:\r\n)
?[ \t])+|\Z|(?=[\[&quot;()&lt;&gt;@,;:\\&quot;.\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t]
)*))*(?:,@(?:(?:\r\n)?[ \t])*(?:[^()&lt;&gt;@,;:\\&quot;.\[\] \000-\031]+(?:(?:(?:\r\n)?[
 \t])+|\Z|(?=[\[&quot;()&lt;&gt;@,;:\\&quot;.\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*
)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()&lt;&gt;@,;:\\&quot;.\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t]
)+|\Z|(?=[\[&quot;()&lt;&gt;@,;:\\&quot;.\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*)
*:(?:(?:\r\n)?[ \t])*)?(?:[^()&lt;&gt;@,;:\\&quot;.\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+
|\Z|(?=[\[&quot;()&lt;&gt;@,;:\\&quot;.\[\]]))|&quot;(?:[^\&quot;\r\\]|\\.|(?:(?:\r\n)?[ \t]))*&quot;(?:(?:\r
\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()&lt;&gt;@,;:\\&quot;.\[\] \000-\031]+(?:(?:(?:
\r\n)?[ \t])+|\Z|(?=[\[&quot;()&lt;&gt;@,;:\\&quot;.\[\]]))|&quot;(?:[^\&quot;\r\\]|\\.|(?:(?:\r\n)?[ \t
]))*&quot;(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()&lt;&gt;@,;:\\&quot;.\[\] \000-\031
]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[&quot;()&lt;&gt;@,;:\\&quot;.\[\]]))|\[([^\[\]\r\\]|\\.)*\](
?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()&lt;&gt;@,;:\\&quot;.\[\] \000-\031]+(?
:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[&quot;()&lt;&gt;@,;:\\&quot;.\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?
:\r\n)?[ \t])*))*\&gt;(?:(?:\r\n)?[ \t])*)|(?:[^()&lt;&gt;@,;:\\&quot;.\[\] \000-\031]+(?:(?
:(?:\r\n)?[ \t])+|\Z|(?=[\[&quot;()&lt;&gt;@,;:\\&quot;.\[\]]))|&quot;(?:[^\&quot;\r\\]|\\.|(?:(?:\r\n)?
[ \t]))*&quot;(?:(?:\r\n)?[ \t])*)*:(?:(?:\r\n)?[ \t])*(?:(?:(?:[^()&lt;&gt;@,;:\\&quot;.\[\]
\000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[&quot;()&lt;&gt;@,;:\\&quot;.\[\]]))|&quot;(?:[^\&quot;\r\\]|
\\.|(?:(?:\r\n)?[ \t]))*&quot;(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()&lt;&gt;
@,;:\\&quot;.\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[&quot;()&lt;&gt;@,;:\\&quot;.\[\]]))|&quot;
(?:[^\&quot;\r\\]|\\.|(?:(?:\r\n)?[ \t]))*&quot;(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t]
)*(?:[^()&lt;&gt;@,;:\\&quot;.\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[&quot;()&lt;&gt;@,;:\\
&quot;.\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?
:[^()&lt;&gt;@,;:\\&quot;.\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[&quot;()&lt;&gt;@,;:\\&quot;.\[
\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*|(?:[^()&lt;&gt;@,;:\\&quot;.\[\] \000-
\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[&quot;()&lt;&gt;@,;:\\&quot;.\[\]]))|&quot;(?:[^\&quot;\r\\]|\\.|(
?:(?:\r\n)?[ \t]))*&quot;(?:(?:\r\n)?[ \t])*)*\&lt;(?:(?:\r\n)?[ \t])*(?:@(?:[^()&lt;&gt;@,;
:\\&quot;.\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[&quot;()&lt;&gt;@,;:\\&quot;.\[\]]))|\[([
^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()&lt;&gt;@,;:\\&quot;
.\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[&quot;()&lt;&gt;@,;:\\&quot;.\[\]]))|\[([^\[\
]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*(?:,@(?:(?:\r\n)?[ \t])*(?:[^()&lt;&gt;@,;:\\&quot;.\
[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[&quot;()&lt;&gt;@,;:\\&quot;.\[\]]))|\[([^\[\]\
r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()&lt;&gt;@,;:\\&quot;.\[\]
\000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[&quot;()&lt;&gt;@,;:\\&quot;.\[\]]))|\[([^\[\]\r\\]
|\\.)*\](?:(?:\r\n)?[ \t])*))*)*:(?:(?:\r\n)?[ \t])*)?(?:[^()&lt;&gt;@,;:\\&quot;.\[\] \0
00-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[&quot;()&lt;&gt;@,;:\\&quot;.\[\]]))|&quot;(?:[^\&quot;\r\\]|\\
.|(?:(?:\r\n)?[ \t]))*&quot;(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()&lt;&gt;@,
;:\\&quot;.\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[&quot;()&lt;&gt;@,;:\\&quot;.\[\]]))|&quot;(?
:[^\&quot;\r\\]|\\.|(?:(?:\r\n)?[ \t]))*&quot;(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*
(?:[^()&lt;&gt;@,;:\\&quot;.\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[&quot;()&lt;&gt;@,;:\\&quot;.
\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[
^()&lt;&gt;@,;:\\&quot;.\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[&quot;()&lt;&gt;@,;:\\&quot;.\[\]
]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*\&gt;(?:(?:\r\n)?[ \t])*)(?:,\s*(
?:(?:[^()&lt;&gt;@,;:\\&quot;.\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[&quot;()&lt;&gt;@,;:\\
&quot;.\[\]]))|&quot;(?:[^\&quot;\r\\]|\\.|(?:(?:\r\n)?[ \t]))*&quot;(?:(?:\r\n)?[ \t])*)(?:\.(?:(
?:\r\n)?[ \t])*(?:[^()&lt;&gt;@,;:\\&quot;.\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[
\[&quot;()&lt;&gt;@,;:\\&quot;.\[\]]))|&quot;(?:[^\&quot;\r\\]|\\.|(?:(?:\r\n)?[ \t]))*&quot;(?:(?:\r\n)?[ \t
])*))*@(?:(?:\r\n)?[ \t])*(?:[^()&lt;&gt;@,;:\\&quot;.\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t
])+|\Z|(?=[\[&quot;()&lt;&gt;@,;:\\&quot;.\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?
:\.(?:(?:\r\n)?[ \t])*(?:[^()&lt;&gt;@,;:\\&quot;.\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|
\Z|(?=[\[&quot;()&lt;&gt;@,;:\\&quot;.\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*|(?:
[^()&lt;&gt;@,;:\\&quot;.\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[&quot;()&lt;&gt;@,;:\\&quot;.\[\
]]))|&quot;(?:[^\&quot;\r\\]|\\.|(?:(?:\r\n)?[ \t]))*&quot;(?:(?:\r\n)?[ \t])*)*\&lt;(?:(?:\r\n)
?[ \t])*(?:@(?:[^()&lt;&gt;@,;:\\&quot;.\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[&quot;
()&lt;&gt;@,;:\\&quot;.\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)
?[ \t])*(?:[^()&lt;&gt;@,;:\\&quot;.\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[&quot;()&lt;&gt;
@,;:\\&quot;.\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*(?:,@(?:(?:\r\n)?[
 \t])*(?:[^()&lt;&gt;@,;:\\&quot;.\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[&quot;()&lt;&gt;@,
;:\\&quot;.\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t]
)*(?:[^()&lt;&gt;@,;:\\&quot;.\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[&quot;()&lt;&gt;@,;:\\
&quot;.\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*)*:(?:(?:\r\n)?[ \t])*)?
(?:[^()&lt;&gt;@,;:\\&quot;.\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[&quot;()&lt;&gt;@,;:\\&quot;.
\[\]]))|&quot;(?:[^\&quot;\r\\]|\\.|(?:(?:\r\n)?[ \t]))*&quot;(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:
\r\n)?[ \t])*(?:[^()&lt;&gt;@,;:\\&quot;.\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[
&quot;()&lt;&gt;@,;:\\&quot;.\[\]]))|&quot;(?:[^\&quot;\r\\]|\\.|(?:(?:\r\n)?[ \t]))*&quot;(?:(?:\r\n)?[ \t])
*))*@(?:(?:\r\n)?[ \t])*(?:[^()&lt;&gt;@,;:\\&quot;.\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])
+|\Z|(?=[\[&quot;()&lt;&gt;@,;:\\&quot;.\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\
.(?:(?:\r\n)?[ \t])*(?:[^()&lt;&gt;@,;:\\&quot;.\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z
|(?=[\[&quot;()&lt;&gt;@,;:\\&quot;.\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*\&gt;(?:(
?:\r\n)?[ \t])*))*)?;\s*)
</pre></div>


<h2>趣事一则</h2>
<p><a href="https://en.wikipedia.org/wiki/ELIZA">ELIZA</a> 是人类史上第一个 “聊天机器人” 程序，上个世纪六十年代，1966 年实现的。核心就是使用正则表达式匹配对方语句中的关键词汇，再经过替换，形成看似有意义的 “回应” —— 事实上，ELIZA 完全不知道自己在说什么……</p>
<p>几年后，就是七十年代初，1972 年，另外一个聊天机器人 <a href="https://en.wikipedia.org/wiki/PARRY">Parry</a> <a href='#fn5' name='fn5b'><sup>[5]</sup></a>被写了出来…… 随后第二年，这两个聊天机器人在 ARPANET “碰面” 好好地聊了一下<a href='#fn6' name='fn6b'><sup>[6]</sup></a>：</p>
<blockquote>
<p>ELIZA: Good Evening. Tell me your problems. Please terminate input with a period or a question mark.</p>
<p>PARRY: People get on my nerves sometimes.</p>
<p>ELIZA: I am not sure I understand you fully.</p>
<p>PARRY: You should pay more attention.</p>
<p>ELIZA: Suppose you should pay more attention.</p>
<p>PARRY: You're entitled to your own opinion.</p>
<p>ELIZA: What makes you think I am entitled to my own opinion?</p>
<p>PARRY: It bothers me just to be around people in general.</p>
<p>ELIZA: Please go on.</p>
<p>PARRY: I went to the track at Bay Meadows a while back.</p>
<p>ELIZA: What does that suggest to you?</p>
<p>PARRY: I went to the races.</p>
<p>......</p>
</blockquote>
<p>以下是后人用 Python 重新实现的 ELIZA 的程序代码，你可以直接执行它，尝试一下与 ELIZA 聊聊天：</p>
<div class="highlight"><pre><span></span><span class="c1"># %load https://raw.githubusercontent.com/jezhiggins/eliza.py/master/eliza.py</span>
<span class="c1">#----------------------------------------------------------------------</span>
<span class="c1">#  eliza.py</span>
<span class="c1">#</span>
<span class="c1">#  a cheezy little Eliza knock-off by Joe Strout</span>
<span class="c1">#  with some updates by Jeff Epler</span>
<span class="c1">#  hacked into a module and updated by Jez Higgins</span>
<span class="c1">#----------------------------------------------------------------------</span>

<span class="kn">import</span> <span class="nn">string</span>
<span class="kn">import</span> <span class="nn">re</span>
<span class="kn">import</span> <span class="nn">random</span>

<span class="k">class</span> <span class="nc">eliza</span><span class="p">:</span>
  <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
    <span class="bp">self</span><span class="o">.</span><span class="n">keys</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="nb">map</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">:</span><span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="n">x</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="n">re</span><span class="o">.</span><span class="n">IGNORECASE</span><span class="p">),</span><span class="n">gPats</span><span class="p">))</span>
    <span class="bp">self</span><span class="o">.</span><span class="n">values</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="nb">map</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">:</span><span class="n">x</span><span class="p">[</span><span class="mi">1</span><span class="p">],</span><span class="n">gPats</span><span class="p">))</span>

  <span class="c1">#----------------------------------------------------------------------</span>
  <span class="c1"># translate: take a string, replace any words found in dict.keys()</span>
  <span class="c1">#  with the corresponding dict.values()</span>
  <span class="c1">#----------------------------------------------------------------------</span>
  <span class="k">def</span> <span class="nf">translate</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span><span class="nb">str</span><span class="p">,</span><span class="nb">dict</span><span class="p">):</span>
    <span class="n">words</span> <span class="o">=</span> <span class="nb">str</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span><span class="o">.</span><span class="n">split</span><span class="p">()</span>
    <span class="n">keys</span> <span class="o">=</span> <span class="nb">dict</span><span class="o">.</span><span class="n">keys</span><span class="p">();</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span><span class="nb">len</span><span class="p">(</span><span class="n">words</span><span class="p">)):</span>
      <span class="k">if</span> <span class="n">words</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="ow">in</span> <span class="n">keys</span><span class="p">:</span>
        <span class="n">words</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">[</span><span class="n">words</span><span class="p">[</span><span class="n">i</span><span class="p">]]</span>
    <span class="k">return</span> <span class="s1">&#39; &#39;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">words</span><span class="p">)</span>

  <span class="c1">#----------------------------------------------------------------------</span>
  <span class="c1">#  respond: take a string, a set of regexps, and a corresponding</span>
  <span class="c1">#    set of response lists; find a match, and return a randomly</span>
  <span class="c1">#    chosen response from the corresponding list.</span>
  <span class="c1">#----------------------------------------------------------------------</span>
  <span class="k">def</span> <span class="nf">respond</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span><span class="nb">str</span><span class="p">):</span>
    <span class="c1"># find a match among keys</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">keys</span><span class="p">)):</span>
      <span class="n">match</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">keys</span><span class="p">[</span><span class="n">i</span><span class="p">]</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="nb">str</span><span class="p">)</span>
      <span class="k">if</span> <span class="n">match</span><span class="p">:</span>
        <span class="c1"># found a match ... stuff with corresponding value</span>
        <span class="c1"># chosen randomly from among the available options</span>
        <span class="n">resp</span> <span class="o">=</span> <span class="n">random</span><span class="o">.</span><span class="n">choice</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">values</span><span class="p">[</span><span class="n">i</span><span class="p">])</span>
        <span class="c1"># we&#39;ve got a response... stuff in reflected text where indicated</span>
        <span class="n">pos</span> <span class="o">=</span> <span class="n">resp</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="s1">&#39;%&#39;</span><span class="p">)</span>
        <span class="k">while</span> <span class="n">pos</span> <span class="o">&gt;</span> <span class="o">-</span><span class="mi">1</span><span class="p">:</span>
          <span class="n">num</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">resp</span><span class="p">[</span><span class="n">pos</span><span class="o">+</span><span class="mi">1</span><span class="p">:</span><span class="n">pos</span><span class="o">+</span><span class="mi">2</span><span class="p">])</span>
          <span class="n">resp</span> <span class="o">=</span> <span class="n">resp</span><span class="p">[:</span><span class="n">pos</span><span class="p">]</span> <span class="o">+</span> \
            <span class="bp">self</span><span class="o">.</span><span class="n">translate</span><span class="p">(</span><span class="n">match</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="n">num</span><span class="p">),</span><span class="n">gReflections</span><span class="p">)</span> <span class="o">+</span> \
            <span class="n">resp</span><span class="p">[</span><span class="n">pos</span><span class="o">+</span><span class="mi">2</span><span class="p">:]</span>
          <span class="n">pos</span> <span class="o">=</span> <span class="n">resp</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="s1">&#39;%&#39;</span><span class="p">)</span>
        <span class="c1"># fix munged punctuation at the end</span>
        <span class="k">if</span> <span class="n">resp</span><span class="p">[</span><span class="o">-</span><span class="mi">2</span><span class="p">:]</span> <span class="o">==</span> <span class="s1">&#39;?.&#39;</span><span class="p">:</span> <span class="n">resp</span> <span class="o">=</span> <span class="n">resp</span><span class="p">[:</span><span class="o">-</span><span class="mi">2</span><span class="p">]</span> <span class="o">+</span> <span class="s1">&#39;.&#39;</span>
        <span class="k">if</span> <span class="n">resp</span><span class="p">[</span><span class="o">-</span><span class="mi">2</span><span class="p">:]</span> <span class="o">==</span> <span class="s1">&#39;??&#39;</span><span class="p">:</span> <span class="n">resp</span> <span class="o">=</span> <span class="n">resp</span><span class="p">[:</span><span class="o">-</span><span class="mi">2</span><span class="p">]</span> <span class="o">+</span> <span class="s1">&#39;?&#39;</span>
        <span class="k">return</span> <span class="n">resp</span>

<span class="c1">#----------------------------------------------------------------------</span>
<span class="c1"># gReflections, a translation table used to convert things you say</span>
<span class="c1">#    into things the computer says back, e.g. &quot;I am&quot; --&gt; &quot;you are&quot;</span>
<span class="c1">#----------------------------------------------------------------------</span>
<span class="n">gReflections</span> <span class="o">=</span> <span class="p">{</span>
  <span class="s2">&quot;am&quot;</span>   <span class="p">:</span> <span class="s2">&quot;are&quot;</span><span class="p">,</span>
  <span class="s2">&quot;was&quot;</span>  <span class="p">:</span> <span class="s2">&quot;were&quot;</span><span class="p">,</span>
  <span class="s2">&quot;i&quot;</span>    <span class="p">:</span> <span class="s2">&quot;you&quot;</span><span class="p">,</span>
  <span class="s2">&quot;i&#39;d&quot;</span>  <span class="p">:</span> <span class="s2">&quot;you would&quot;</span><span class="p">,</span>
  <span class="s2">&quot;i&#39;ve&quot;</span>  <span class="p">:</span> <span class="s2">&quot;you have&quot;</span><span class="p">,</span>
  <span class="s2">&quot;i&#39;ll&quot;</span>  <span class="p">:</span> <span class="s2">&quot;you will&quot;</span><span class="p">,</span>
  <span class="s2">&quot;my&quot;</span>  <span class="p">:</span> <span class="s2">&quot;your&quot;</span><span class="p">,</span>
  <span class="s2">&quot;are&quot;</span>  <span class="p">:</span> <span class="s2">&quot;am&quot;</span><span class="p">,</span>
  <span class="s2">&quot;you&#39;ve&quot;</span><span class="p">:</span> <span class="s2">&quot;I have&quot;</span><span class="p">,</span>
  <span class="s2">&quot;you&#39;ll&quot;</span><span class="p">:</span> <span class="s2">&quot;I will&quot;</span><span class="p">,</span>
  <span class="s2">&quot;your&quot;</span>  <span class="p">:</span> <span class="s2">&quot;my&quot;</span><span class="p">,</span>
  <span class="s2">&quot;yours&quot;</span>  <span class="p">:</span> <span class="s2">&quot;mine&quot;</span><span class="p">,</span>
  <span class="s2">&quot;you&quot;</span>  <span class="p">:</span> <span class="s2">&quot;me&quot;</span><span class="p">,</span>
  <span class="s2">&quot;me&quot;</span>  <span class="p">:</span> <span class="s2">&quot;you&quot;</span>
<span class="p">}</span>

<span class="c1">#----------------------------------------------------------------------</span>
<span class="c1"># gPats, the main response table.  Each element of the list is a</span>
<span class="c1">#  two-element list; the first is a regexp, and the second is a</span>
<span class="c1">#  list of possible responses, with group-macros labelled as</span>
<span class="c1">#  %1, %2, etc.</span>
<span class="c1">#----------------------------------------------------------------------</span>
<span class="n">gPats</span> <span class="o">=</span> <span class="p">[</span>
  <span class="p">[</span><span class="sa">r</span><span class="s1">&#39;I need (.*)&#39;</span><span class="p">,</span>
  <span class="p">[</span>  <span class="s2">&quot;Why do you need %1?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Would it really help you to get %1?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Are you sure you need %1?&quot;</span><span class="p">]],</span>

  <span class="p">[</span><span class="sa">r</span><span class="s1">&#39;Why don</span><span class="se">\&#39;</span><span class="s1">?t you ([^\?]*)\??&#39;</span><span class="p">,</span>
  <span class="p">[</span>  <span class="s2">&quot;Do you really think I don&#39;t %1?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Perhaps eventually I will %1.&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Do you really want me to %1?&quot;</span><span class="p">]],</span>

  <span class="p">[</span><span class="sa">r</span><span class="s1">&#39;Why can</span><span class="se">\&#39;</span><span class="s1">?t I ([^\?]*)\??&#39;</span><span class="p">,</span>
  <span class="p">[</span>  <span class="s2">&quot;Do you think you should be able to %1?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;If you could %1, what would you do?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;I don&#39;t know -- why can&#39;t you %1?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Have you really tried?&quot;</span><span class="p">]],</span>

  <span class="p">[</span><span class="sa">r</span><span class="s1">&#39;I can</span><span class="se">\&#39;</span><span class="s1">?t (.*)&#39;</span><span class="p">,</span>
  <span class="p">[</span>  <span class="s2">&quot;How do you know you can&#39;t %1?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Perhaps you could %1 if you tried.&quot;</span><span class="p">,</span>
    <span class="s2">&quot;What would it take for you to %1?&quot;</span><span class="p">]],</span>

  <span class="p">[</span><span class="sa">r</span><span class="s1">&#39;I am (.*)&#39;</span><span class="p">,</span>
  <span class="p">[</span>  <span class="s2">&quot;Did you come to me because you are %1?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;How long have you been %1?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;How do you feel about being %1?&quot;</span><span class="p">]],</span>

  <span class="p">[</span><span class="sa">r</span><span class="s1">&#39;I</span><span class="se">\&#39;</span><span class="s1">?m (.*)&#39;</span><span class="p">,</span>
  <span class="p">[</span>  <span class="s2">&quot;How does being %1 make you feel?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Do you enjoy being %1?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Why do you tell me you&#39;re %1?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Why do you think you&#39;re %1?&quot;</span><span class="p">]],</span>

  <span class="p">[</span><span class="sa">r</span><span class="s1">&#39;Are you ([^\?]*)\??&#39;</span><span class="p">,</span>
  <span class="p">[</span>  <span class="s2">&quot;Why does it matter whether I am %1?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Would you prefer it if I were not %1?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Perhaps you believe I am %1.&quot;</span><span class="p">,</span>
    <span class="s2">&quot;I may be %1 -- what do you think?&quot;</span><span class="p">]],</span>

  <span class="p">[</span><span class="sa">r</span><span class="s1">&#39;What (.*)&#39;</span><span class="p">,</span>
  <span class="p">[</span>  <span class="s2">&quot;Why do you ask?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;How would an answer to that help you?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;What do you think?&quot;</span><span class="p">]],</span>

  <span class="p">[</span><span class="sa">r</span><span class="s1">&#39;How (.*)&#39;</span><span class="p">,</span>
  <span class="p">[</span>  <span class="s2">&quot;How do you suppose?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Perhaps you can answer your own question.&quot;</span><span class="p">,</span>
    <span class="s2">&quot;What is it you&#39;re really asking?&quot;</span><span class="p">]],</span>

  <span class="p">[</span><span class="sa">r</span><span class="s1">&#39;Because (.*)&#39;</span><span class="p">,</span>
  <span class="p">[</span>  <span class="s2">&quot;Is that the real reason?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;What other reasons come to mind?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Does that reason apply to anything else?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;If %1, what else must be true?&quot;</span><span class="p">]],</span>

  <span class="p">[</span><span class="sa">r</span><span class="s1">&#39;(.*) sorry (.*)&#39;</span><span class="p">,</span>
  <span class="p">[</span>  <span class="s2">&quot;There are many times when no apology is needed.&quot;</span><span class="p">,</span>
    <span class="s2">&quot;What feelings do you have when you apologize?&quot;</span><span class="p">]],</span>

  <span class="p">[</span><span class="sa">r</span><span class="s1">&#39;Hello(.*)&#39;</span><span class="p">,</span>
  <span class="p">[</span>  <span class="s2">&quot;Hello... I&#39;m glad you could drop by today.&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Hi there... how are you today?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Hello, how are you feeling today?&quot;</span><span class="p">]],</span>

  <span class="p">[</span><span class="sa">r</span><span class="s1">&#39;I think (.*)&#39;</span><span class="p">,</span>
  <span class="p">[</span>  <span class="s2">&quot;Do you doubt %1?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Do you really think so?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;But you&#39;re not sure %1?&quot;</span><span class="p">]],</span>

  <span class="p">[</span><span class="sa">r</span><span class="s1">&#39;(.*) friend (.*)&#39;</span><span class="p">,</span>
  <span class="p">[</span>  <span class="s2">&quot;Tell me more about your friends.&quot;</span><span class="p">,</span>
    <span class="s2">&quot;When you think of a friend, what comes to mind?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Why don&#39;t you tell me about a childhood friend?&quot;</span><span class="p">]],</span>

  <span class="p">[</span><span class="sa">r</span><span class="s1">&#39;Yes&#39;</span><span class="p">,</span>
  <span class="p">[</span>  <span class="s2">&quot;You seem quite sure.&quot;</span><span class="p">,</span>
    <span class="s2">&quot;OK, but can you elaborate a bit?&quot;</span><span class="p">]],</span>

  <span class="p">[</span><span class="sa">r</span><span class="s1">&#39;(.*) computer(.*)&#39;</span><span class="p">,</span>
  <span class="p">[</span>  <span class="s2">&quot;Are you really talking about me?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Does it seem strange to talk to a computer?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;How do computers make you feel?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Do you feel threatened by computers?&quot;</span><span class="p">]],</span>

  <span class="p">[</span><span class="sa">r</span><span class="s1">&#39;Is it (.*)&#39;</span><span class="p">,</span>
  <span class="p">[</span>  <span class="s2">&quot;Do you think it is %1?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Perhaps it&#39;s %1 -- what do you think?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;If it were %1, what would you do?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;It could well be that %1.&quot;</span><span class="p">]],</span>

  <span class="p">[</span><span class="sa">r</span><span class="s1">&#39;It is (.*)&#39;</span><span class="p">,</span>
  <span class="p">[</span>  <span class="s2">&quot;You seem very certain.&quot;</span><span class="p">,</span>
    <span class="s2">&quot;If I told you that it probably isn&#39;t %1, what would you feel?&quot;</span><span class="p">]],</span>

  <span class="p">[</span><span class="sa">r</span><span class="s1">&#39;Can you ([^\?]*)\??&#39;</span><span class="p">,</span>
  <span class="p">[</span>  <span class="s2">&quot;What makes you think I can&#39;t %1?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;If I could %1, then what?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Why do you ask if I can %1?&quot;</span><span class="p">]],</span>

  <span class="p">[</span><span class="sa">r</span><span class="s1">&#39;Can I ([^\?]*)\??&#39;</span><span class="p">,</span>
  <span class="p">[</span>  <span class="s2">&quot;Perhaps you don&#39;t want to %1.&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Do you want to be able to %1?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;If you could %1, would you?&quot;</span><span class="p">]],</span>

  <span class="p">[</span><span class="sa">r</span><span class="s1">&#39;You are (.*)&#39;</span><span class="p">,</span>
  <span class="p">[</span>  <span class="s2">&quot;Why do you think I am %1?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Does it please you to think that I&#39;m %1?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Perhaps you would like me to be %1.&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Perhaps you&#39;re really talking about yourself?&quot;</span><span class="p">]],</span>

  <span class="p">[</span><span class="sa">r</span><span class="s1">&#39;You</span><span class="se">\&#39;</span><span class="s1">?re (.*)&#39;</span><span class="p">,</span>
  <span class="p">[</span>  <span class="s2">&quot;Why do you say I am %1?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Why do you think I am %1?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Are we talking about you, or me?&quot;</span><span class="p">]],</span>

  <span class="p">[</span><span class="sa">r</span><span class="s1">&#39;I don</span><span class="se">\&#39;</span><span class="s1">?t (.*)&#39;</span><span class="p">,</span>
  <span class="p">[</span>  <span class="s2">&quot;Don&#39;t you really %1?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Why don&#39;t you %1?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Do you want to %1?&quot;</span><span class="p">]],</span>

  <span class="p">[</span><span class="sa">r</span><span class="s1">&#39;I feel (.*)&#39;</span><span class="p">,</span>
  <span class="p">[</span>  <span class="s2">&quot;Good, tell me more about these feelings.&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Do you often feel %1?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;When do you usually feel %1?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;When you feel %1, what do you do?&quot;</span><span class="p">]],</span>

  <span class="p">[</span><span class="sa">r</span><span class="s1">&#39;I have (.*)&#39;</span><span class="p">,</span>
  <span class="p">[</span>  <span class="s2">&quot;Why do you tell me that you&#39;ve %1?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Have you really %1?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Now that you have %1, what will you do next?&quot;</span><span class="p">]],</span>

  <span class="p">[</span><span class="sa">r</span><span class="s1">&#39;I would (.*)&#39;</span><span class="p">,</span>
  <span class="p">[</span>  <span class="s2">&quot;Could you explain why you would %1?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Why would you %1?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Who else knows that you would %1?&quot;</span><span class="p">]],</span>

  <span class="p">[</span><span class="sa">r</span><span class="s1">&#39;Is there (.*)&#39;</span><span class="p">,</span>
  <span class="p">[</span>  <span class="s2">&quot;Do you think there is %1?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;It&#39;s likely that there is %1.&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Would you like there to be %1?&quot;</span><span class="p">]],</span>

  <span class="p">[</span><span class="sa">r</span><span class="s1">&#39;My (.*)&#39;</span><span class="p">,</span>
  <span class="p">[</span>  <span class="s2">&quot;I see, your %1.&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Why do you say that your %1?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;When your %1, how do you feel?&quot;</span><span class="p">]],</span>

  <span class="p">[</span><span class="sa">r</span><span class="s1">&#39;You (.*)&#39;</span><span class="p">,</span>
  <span class="p">[</span>  <span class="s2">&quot;We should be discussing you, not me.&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Why do you say that about me?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Why do you care whether I %1?&quot;</span><span class="p">]],</span>

  <span class="p">[</span><span class="sa">r</span><span class="s1">&#39;Why (.*)&#39;</span><span class="p">,</span>
  <span class="p">[</span>  <span class="s2">&quot;Why don&#39;t you tell me the reason why %1?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Why do you think %1?&quot;</span> <span class="p">]],</span>

  <span class="p">[</span><span class="sa">r</span><span class="s1">&#39;I want (.*)&#39;</span><span class="p">,</span>
  <span class="p">[</span>  <span class="s2">&quot;What would it mean to you if you got %1?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Why do you want %1?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;What would you do if you got %1?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;If you got %1, then what would you do?&quot;</span><span class="p">]],</span>

  <span class="p">[</span><span class="sa">r</span><span class="s1">&#39;(.*) mother(.*)&#39;</span><span class="p">,</span>
  <span class="p">[</span>  <span class="s2">&quot;Tell me more about your mother.&quot;</span><span class="p">,</span>
    <span class="s2">&quot;What was your relationship with your mother like?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;How do you feel about your mother?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;How does this relate to your feelings today?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Good family relations are important.&quot;</span><span class="p">]],</span>

  <span class="p">[</span><span class="sa">r</span><span class="s1">&#39;(.*) father(.*)&#39;</span><span class="p">,</span>
  <span class="p">[</span>  <span class="s2">&quot;Tell me more about your father.&quot;</span><span class="p">,</span>
    <span class="s2">&quot;How did your father make you feel?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;How do you feel about your father?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Does your relationship with your father relate to your feelings today?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Do you have trouble showing affection with your family?&quot;</span><span class="p">]],</span>

  <span class="p">[</span><span class="sa">r</span><span class="s1">&#39;(.*) child(.*)&#39;</span><span class="p">,</span>
  <span class="p">[</span>  <span class="s2">&quot;Did you have close friends as a child?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;What is your favorite childhood memory?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Do you remember any dreams or nightmares from childhood?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Did the other children sometimes tease you?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;How do you think your childhood experiences relate to your feelings today?&quot;</span><span class="p">]],</span>

  <span class="p">[</span><span class="sa">r</span><span class="s1">&#39;(.*)\?&#39;</span><span class="p">,</span>
  <span class="p">[</span>  <span class="s2">&quot;Why do you ask that?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Please consider whether you can answer your own question.&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Perhaps the answer lies within yourself?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Why don&#39;t you tell me?&quot;</span><span class="p">]],</span>

  <span class="p">[</span><span class="sa">r</span><span class="s1">&#39;quit&#39;</span><span class="p">,</span>
  <span class="p">[</span>  <span class="s2">&quot;Thank you for talking with me.&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Good-bye.&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Thank you, that will be $150.  Have a good day!&quot;</span><span class="p">]],</span>

  <span class="p">[</span><span class="sa">r</span><span class="s1">&#39;(.*)&#39;</span><span class="p">,</span>
  <span class="p">[</span>  <span class="s2">&quot;Please tell me more.&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Let&#39;s change focus a bit... Tell me about your family.&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Can you elaborate on that?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Why do you say that %1?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;I see.&quot;</span><span class="p">,</span>
    <span class="s2">&quot;Very interesting.&quot;</span><span class="p">,</span>
    <span class="s2">&quot;%1.&quot;</span><span class="p">,</span>
    <span class="s2">&quot;I see.  And what does that tell you?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;How does that make you feel?&quot;</span><span class="p">,</span>
    <span class="s2">&quot;How do you feel when you say that?&quot;</span><span class="p">]]</span>
  <span class="p">]</span>

<span class="c1">#----------------------------------------------------------------------</span>
<span class="c1">#  command_interface</span>
<span class="c1">#----------------------------------------------------------------------</span>
<span class="k">def</span> <span class="nf">command_interface</span><span class="p">():</span>
  <span class="k">print</span><span class="p">(</span><span class="s1">&#39;Therapist</span><span class="se">\n</span><span class="s1">---------&#39;</span><span class="p">)</span>
  <span class="k">print</span><span class="p">(</span><span class="s1">&#39;Talk to the program by typing in plain English, using normal upper-&#39;</span><span class="p">)</span>
  <span class="k">print</span><span class="p">(</span><span class="s1">&#39;and lower-case letters and punctuation.  Enter &quot;quit&quot; when done.&#39;</span><span class="p">)</span>
  <span class="k">print</span><span class="p">(</span><span class="s1">&#39;=&#39;</span><span class="o">*</span><span class="mi">72</span><span class="p">)</span>
  <span class="k">print</span><span class="p">(</span><span class="s1">&#39;Hello.  How are you feeling today?&#39;</span><span class="p">)</span>

  <span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span>
  <span class="n">therapist</span> <span class="o">=</span> <span class="n">eliza</span><span class="p">();</span>
  <span class="k">while</span> <span class="n">s</span> <span class="o">!=</span> <span class="s1">&#39;quit&#39;</span><span class="p">:</span>
    <span class="k">try</span><span class="p">:</span>
      <span class="n">s</span> <span class="o">=</span> <span class="nb">input</span><span class="p">(</span><span class="s1">&#39;&gt; &#39;</span><span class="p">)</span>
    <span class="k">except</span> <span class="ne">EOFError</span><span class="p">:</span>
      <span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;quit&#39;</span>
    <span class="k">print</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
    <span class="k">while</span> <span class="n">s</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span> <span class="ow">in</span> <span class="s1">&#39;!.&#39;</span><span class="p">:</span>
      <span class="n">s</span> <span class="o">=</span> <span class="n">s</span><span class="p">[:</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
    <span class="k">print</span><span class="p">(</span><span class="n">therapist</span><span class="o">.</span><span class="n">respond</span><span class="p">(</span><span class="n">s</span><span class="p">))</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s2">&quot;__main__&quot;</span><span class="p">:</span>
  <span class="n">command_interface</span><span class="p">()</span>
</pre></div>


<div class="highlight"><pre><span></span><span class="gh">Therapist</span>
<span class="gh">---------</span>
Talk to the program by typing in plain English, using normal upper-
<span class="gh">and lower-case letters and punctuation.  Enter &quot;quit&quot; when done.</span>
<span class="gh">========================================================================</span>
Hello.  How are you feeling today?
</pre></div>


<hr>
<p><strong>脚注</strong></p>
<p><a name='fn1'>[1]</a>：释义摘自苹果电脑上系统内建的《牛津英汉双解辞典》</p>
<p><a href='#fn1b'><small>↑Back to Content↑</small></a></p>
<p><a name='fn2'>[2]</a>：<a href="https://bit.ly/2tz8v9n">8 Regular Expressions You Should Know</a> by Vasili</p>
<p><a href='#fn2b'><small>↑Back to Content↑</small></a></p>
<p><a name='fn3'>[3]</a>：关于校验密码强度的正则表达式，往往需要设置更为复杂的规则，Stackoverflow 上的一则答复中有很好的示例：https://stackoverflow.com/a/21456918</p>
<p><a href='#fn3b'><small>↑Back to Content↑</small></a></p>
<p><a name='fn4'>[4]</a>：http://www.ex-parrot.com/pdw/Mail-RFC822-Address.html</p>
<p><a href='#fn4b'><small>↑Back to Content↑</small></a></p>
<p><a name='fn5'>[5]</a>：Parry 的源代码（用 Lisp 写的）在这里：http://www.cs.cmu.edu/afs/cs/project/ai-repository/ai/areas/classics/parry/</a></p>
<p><a href='#fn5b'><small>↑Back to Content↑</small></a></p>
<p><a name='fn6'>[6]</a>：ELIZA 和 Parry 的完整聊天记录在这里：https://tools.ietf.org/html/rfc439</a></p>
<p><a href='#fn6b'><small>↑Back to Content↑</small></a></p>
    </div><!-- /.entry-content -->

  </article>
</section>
        <section id="extras" class="body">
                <div class="blogroll">
                        <h2>blogroll</h2>
                        <ul>
                            <li><a href="http://getpelican.com/">Pelican</a></li>
                            <li><a href="http://python.org/">Python.org</a></li>
                            <li><a href="http://jinja.pocoo.org/">Jinja2</a></li>
                            <li><a href="#">You can modify those links in your config file</a></li>
                        </ul>
                </div><!-- /.blogroll -->
                <div class="social">
                        <h2>social</h2>
                        <ul>

                            <li><a href="#">You can add links in your config file</a></li>
                            <li><a href="#">Another social link</a></li>
                        </ul>
                </div><!-- /.social -->
        </section><!-- /#extras -->

        <footer id="contentinfo" class="body">
                <p>Powered by <a href="http://www.maxiaoan.com/">Maxiaoan</a></p>
        </footer><!-- /#contentinfo -->

</body>
</html>